package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author alexis
 * @date 2025-11-13
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${alert.deviceRole}")
    private String deviceRole;
    @Value("${alert.managerRole}")
    private String managerRole;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void alertFilter() {
        LambdaQueryWrapper<AlertRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlertRule::getStatus, 1);
        long count = count(wrapper);
        if(count < 1){
            return;
        }

        List values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_DATA_LAST);
        if(CollUtil.isEmpty( values)){
            return;
        }

        ArrayList<DeviceData> list = new ArrayList<>();
        values.forEach(v -> {
            List<DeviceData> dataList = JSONUtil.toList(v.toString(), DeviceData.class);
            list.addAll(dataList);
        });

        list.forEach(d -> { alertDataFilter(d);
        });

    }

    private void alertDataFilter(DeviceData deviceData) {
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if(between > 60){
            return;
        }

        LambdaQueryWrapper<AlertRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getStatus, 1);
        List<AlertRule> alertRulesAll = list(wrapper);

        LambdaQueryWrapper<AlertRule> wrapper2 = new LambdaQueryWrapper<AlertRule>();
        wrapper2.eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1);
        List<AlertRule> alertRules = list(wrapper2);

        Collection<AlertRule> allRules = CollUtil.addAll(alertRulesAll, alertRules);
        if(CollUtil.isEmpty(allRules)){
            return;
        }
        allRules.forEach(a -> {deviceAlertHandler(a, deviceData);});
    }

    private void deviceAlertHandler(AlertRule alertRule, DeviceData deviceData) {
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);

        LocalTime time = deviceData.getAlarmTime().toLocalTime();
        if(time.isBefore(startTime) || time.isAfter(endTime)){
            return;
        }

        String iotId = deviceData.getIotId();
        String aggCountKey=CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+iotId+":"+deviceData.getFunctionId()
                +":"+alertRule.getId();

        int compare = NumberUtil.compare(Double.valueOf(deviceData.getDataValue()), alertRule.getValue());
        if((alertRule.getOperator().equals(">=")&&compare >= 0)
            || (alertRule.getOperator().equals("<")&&compare < 0)){
            log.info("当前上报的数据符合条件规则---->异常数据");
        }else {
            redisTemplate.delete(aggCountKey);
            return;
        }

        String silentKey = CacheConstants.ALERT_SILENCE_PREFIX+iotId+":"+deviceData.getIotId()+":"+alertRule.getId();
        String silentValue = redisTemplate.opsForValue().get(silentKey);
        if(StringUtils.isNotEmpty(silentValue)){
            return;
        }
        String aggCountStr = redisTemplate.opsForValue().get(aggCountKey);
        int aggCount = StringUtils.isEmpty(aggCountStr)?1:Integer.valueOf(aggCountStr)+1;
        if(ObjectUtil.notEqual(aggCount,alertRule.getDuration())){
            redisTemplate.opsForValue().set(aggCountKey, aggCount+ "");
        }

        redisTemplate.delete(aggCountKey);
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);


        List<Long> userIds = new ArrayList<>();

        if(alertRule.getAlertDataType().equals(0)){
            if(deviceData.getLocationType().equals(0)){
                userIds=deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            }else if(deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals("2")){
                userIds=deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }else {
            userIds=sysUserRoleMapper.selectUserIdByRoleName(deviceRole);
        }
        List<Long> managerIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);
        allUserIds = CollUtil.distinct(allUserIds);
        insertAlertData(allUserIds,alertRule,deviceData);
    }

    @Autowired
    private IAlertDataService alertDataService;

    private void insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        String reason = CharSequenceUtil.format("{}{}{},持续{}个周期",
                deviceData.getFunctionId(),alertRule.getOperator(),alertRule.getValue(),
                alertRule.getDuration());
        alertData.setAlertReason(reason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setAlertRuleId(alertRule.getId());

        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData alertData1 = BeanUtil.toBean(alertData, AlertData.class);
            alertData1.setUserId(userId);
            alertData1.setId(null);
            return alertData1;
        }).collect(Collectors.toList());

        alertDataService.saveBatch(list);

    }
}
